package eco.footprint;

import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.Date;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Images.Media;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class FootprintSummaryActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.summary);
		Intent intent = getIntent();
		FootprintResult r = intent.getParcelableExtra("result");
		double planets = r.numberOfEarths;

		String resultTemplate = getResources().getString(
				R.string.strResultTemplate);
		String additional = "";

		if (planets < 1)
			additional = getResources().getString(R.string.strBestResult);
		else if (planets < 2)
			additional = getResources().getString(R.string.strGoodResult);
		else if (planets < 4)
			additional = getResources().getString(R.string.strAverageResult);
		else
			additional = getResources().getString(R.string.strBadResult);

		String resultText = MessageFormat.format(resultTemplate, planets,
				additional);

		TextView txtSummary = (TextView) findViewById(R.id.txtSummary);
		txtSummary.setText(resultText);

		double mVal = 0;
		double mTextWidth = 0;
		double[] values = { r.energyTotal, r.cropTotal, r.grazTotal,
				r.forestTotal, r.builtTotal, r.fishTotal };
		String energy = getResources().getString(R.string.lbEnergy);
		String crop = getResources().getString(R.string.lbCrop);
		String graz = getResources().getString(R.string.lbGraz);
		String forest = getResources().getString(R.string.lbForest);
		String built = getResources().getString(R.string.lbBuilt);
		String fish = getResources().getString(R.string.lbFish);
		String[] labels = { energy, crop, graz, forest, built, fish };

		for (int i = 0; i < values.length; i++)
			mVal = Math.max(mVal, values[i]);

		for (int i = 0; i < values.length; i++) {
			Paint p = new Paint();
			p.setTextSize(15);
			mTextWidth = Math.max(p.measureText(labels[i]), mTextWidth);
		}

		LinearLayout indResources = (LinearLayout) findViewById(R.id.indResources);

		for (int i = 0; i < values.length; i++)
			indResources.addView(createIndicator(mTextWidth, mVal, labels[i],
					values[i]));

		double[] areaValues = { r.foodTotal, r.shelterTotal, r.mobilityTotal,
				r.goodsTotal, r.servicesTotal, r.governanceTotal };
		String food = getResources().getString(R.string.lbFood);
		String shelter = getResources().getString(R.string.lbShelter);
		String mobility = getResources().getString(R.string.lbMobility);
		String goods = getResources().getString(R.string.lbGoods);
		String services = getResources().getString(R.string.lbServices);
		String governance = getResources().getString(R.string.lbGovernance);
		String[] areaLabels = { food, shelter, mobility, goods, services,
				governance };

		for (int i = 0; i < areaValues.length; i++)
			mVal = Math.max(mVal, areaValues[i]);

		for (int i = 0; i < areaValues.length; i++) {
			Paint p = new Paint();
			p.setTextSize(15);
			mTextWidth = Math.max(p.measureText(areaLabels[i]), mTextWidth);
		}

		LinearLayout indAreas = (LinearLayout) findViewById(R.id.indAreas);

		for (int i = 0; i < areaValues.length; i++)
			indAreas.addView(createIndicator(mTextWidth, mVal, areaLabels[i],
					areaValues[i]));

		generateIndicator(r.numberOfEarths);

		final Bitmap userbar = generateBanner(r.numberOfEarths);

		ImageButton btnShare = (ImageButton) findViewById(R.id.btnShare);
		btnShare.setImageBitmap(userbar);
		btnShare.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				Uri uri = storeUserbar(userbar);
				Date now = new Date(System.currentTimeMillis());
				String date = DateFormat.getDateFormat(
						FootprintSummaryActivity.this).format(now)
						+ " "
						+ DateFormat.getTimeFormat(
								FootprintSummaryActivity.this).format(now);
				Intent i = new Intent(Intent.ACTION_SEND);
				i.putExtra(Intent.EXTRA_SUBJECT, "ecoFootprint userbar");
				i.putExtra(Intent.EXTRA_STREAM, uri);
				i.putExtra(Intent.EXTRA_TEXT,
						"Hi!\nThis ecoFootprint userbar generated " + date);
				i.setType("image/jpeg");
				startActivity(Intent.createChooser(i, getResources().getText(
						R.string.lbSend)));

			}
		});

		TextView tipsTextView = (TextView) findViewById(R.id.txtTips);
		String tipsText = "";
		String[] tips = intent.getStringArrayExtra("tips");
		for (int k = 0; k < 3; k++) {
			tipsText += tips[k];
			tipsText += "\n";
		}
		tipsTextView.setText(tipsText);

		Button btnBack = (Button) findViewById(R.id.btnSummaryBack);
		btnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				setResult(RESULT_CANCELED);
				finish();
			}
		});

		Button btnExit = (Button) findViewById(R.id.btnSummaryExit);
		btnExit.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				setResult(RESULT_OK);
				finish();
			}
		});
	}

	private LinearLayout createIndicator(double textMaxWidth, double maxValue,
			String name, double value) {
		double coef = value / maxValue;
		LinearLayout indicator = new LinearLayout(this);
		indicator.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		indicator.setGravity(Gravity.CENTER_VERTICAL);

		TextView text = new TextView(this);
		text.setTextSize(15);
		text.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));

		text.setText(name);
		text.setTextColor(getResources().getColor(R.color.textColor));
		indicator.addView(text, 0);
		ImageView image = new ImageView(this);
		Bitmap barDark = BitmapFactory.decodeResource(getResources(),
				R.drawable.bar_old);
		Bitmap barLight = BitmapFactory.decodeResource(getResources(),
				R.drawable.bar_new);
		image.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT));
		indicator.addView(image, 1);

		Paint p = new Paint();

		p.setTextSize(text.getTextSize());
		int width = getWindowManager().getDefaultDisplay().getWidth();
		width -= textMaxWidth + 50;
		text.setPadding((int) (textMaxWidth - p.measureText(name) + 40), 0, 0,
				0);
		int dw = barLight.getScaledWidth(getResources().getDisplayMetrics()) / 2;
		int h = barLight.getScaledHeight(getResources().getDisplayMetrics());
		Bitmap bitmap = Bitmap.createBitmap(width, h, Config.RGB_565);
		int cnt = (int) Math.round(((((double) width) / dw) * coef)
				- Math.round(1 * coef));
		Canvas canvas = new Canvas(bitmap);
		canvas.drawColor(getResources().getColor(R.color.bg2Color));
		int x = 0;
		for (int i = 0; i < cnt; i++) {
			canvas.drawBitmap(barLight, x, 0, p);
			x += dw;
		}

		int cntAll = (int) Math.round((((double) width) / dw) - 1);

		for (int i = cnt; i < cntAll; i++) {
			canvas.drawBitmap(barDark, x, 0, p);
			x += dw;
		}
		image.setImageBitmap(bitmap);
		return indicator;
	}

	private void generateIndicator(double numberOfEarths) {
		int ceil = (int) Math.ceil(numberOfEarths);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.earth);
		bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true);
		int dw = bitmap.getWidth();
		int h = bitmap.getHeight();
		int w = (int) Math.ceil(dw * numberOfEarths);
		Bitmap result = Bitmap.createBitmap(w, h, Config.RGB_565);
		Canvas canvas = new Canvas(result);
		canvas.drawColor(getResources().getColor(R.color.bg2Color));
		int x = 0;
		Paint p = new Paint();
		for (int i = 0; i < ceil; i++) {
			canvas.drawBitmap(bitmap, x, 0, p);
			x += dw;
		}
		ImageView imgEarth = (ImageView) findViewById(R.id.imgSummaryEarth);
		imgEarth.setImageBitmap(result);
	}

	private Bitmap generateBanner(double numberOfEarths) {
		Bitmap result = Bitmap.createBitmap(350, 19, Config.RGB_565);
		Drawable userbar = getResources().getDrawable(R.drawable.userbar);
		Canvas canvas = new Canvas(result);
		userbar.setBounds(0, 0, 350, 19);
		userbar.draw(canvas);
		Paint paint = new Paint();
		paint.setTextSize(40);
		paint.setColor(Color.WHITE);
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"fonts/visitor2.ttf");
		paint.setTypeface(typeface);

		int ceil = (int) Math.ceil(numberOfEarths);
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.earth_glow);
		bitmap = Bitmap.createScaledBitmap(bitmap, 19, 19, true);
		int dw = bitmap.getWidth();
		int x = 350 - (int) Math.ceil(dw * numberOfEarths);
		Paint p = new Paint();
		for (int i = 0; i < ceil; i++) {
			canvas.drawBitmap(bitmap, x, 0, p);
			x += dw;
		}
		canvas.drawText(MessageFormat.format("{0, number, #.##}",
				numberOfEarths), 130, 17, paint);
		return result;
	}

	private Uri storeUserbar(Bitmap bitmap) {
		ContentValues values = new ContentValues(3);
		values.put(Media.DISPLAY_NAME, "ecofootprint_userbar.jpg");
		values.put(Media.TITLE, "ecofootprint_userbar.jpg");
		values.put(Media.DESCRIPTION, "ecofootprint userbar");
		values.put(Media.MIME_TYPE, "image/jpeg");
		Uri saveUri = Media.EXTERNAL_CONTENT_URI;

		Cursor cur = managedQuery(saveUri, new String[] { MediaColumns._ID },
				MessageFormat.format("{0} = \"{1}\"", MediaColumns.TITLE,
						"ecofootprint_userbar.jpg"), null, null);
		Uri uri = null;
		if (cur.getCount() > 0) {
			cur.moveToFirst();
			long id = cur.getLong(cur.getColumnIndex(MediaColumns._ID));
			uri = Uri.withAppendedPath(saveUri, String.valueOf(id));

		} else {
			uri = getContentResolver().insert(saveUri, values);
		}
		try {
			OutputStream outStream = getContentResolver().openOutputStream(uri);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
			outStream.close();
		} catch (Exception e) {
			Log.e("ecoFootprint", "exception while writing image", e);
		}
		return uri;
	}

}
